let ip = global_config["ip"]
let api_port_path = global_config["api_port_path"]
let api_port_1 = global_config["api_port_1"]
let car_run = {}
let car_paths = {}
let car_v = 30

// 登陆状态
let user = localStorage.getItem("user")
if (user) {
    $("body").css({ display: "inline" })
} else {
    window.location.href = './login.html'
}


// ----------------高德地图------------------------------
let map = new AMap.Map('map', {
    zoom: 15,
    zooms:[14,18],
    center: [106.463559, 29.56507],
    zIndex: -1
});

// ---------------------右-------------------------------------------
// ajax封装
function ajax_method(url, data, method, success) {
    // 异步对象
    let ajax = new XMLHttpRequest();

    // get 跟post  需要分别写不同的代码
    if (method == 'get') {
        // get请求
        if (data) {
            // 如果有值
            // url += '?';
            url += '/';
            url += data;
        } else {
        }
        // 设置 方法 以及 url
        ajax.open(method, url);

        // send即可
        ajax.send();
    } else {
        // post请求
        // post请求 url 是不需要改变
        ajax.open(method, url);

        // 需要设置请求报文
        ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        // 判断data send发送数据
        if (data) {
            // 如果有值 从send发送
            ajax.send(data);
        } else {
            // 木有值 直接发送即可
            ajax.send();
        }
    }

    // 注册事件
    ajax.onreadystatechange = function () {
        // 在事件中 获取数据 并修改界面显示
        if (ajax.readyState == 4 && ajax.status == 200) {
            success(ajax.responseText);
        }
    }

}
// 右侧车辆信息盒
let car_data = document.querySelector("#dir_data")

// 预显示车辆
function initcar() {
    let url = ip + ":" + api_port_1 + "/get_init_car"
    ajax_method(url, null, "Get", (data) => {
        $('#dir_data').html('')
        let car_json = JSON.parse(data)
        let str = ""
        for (let i = 1; i < car_json.length; i++) {
            str += '<div class="car_row car_row_li">' +
                '<div class="car_d1">' + car_json[i][1] + '</div>' +
                '<div class="car_d2">' + car_json[i][2] + '</div>' +
                '<img src="img/+.png" alt="添加到显示" title="添加到显示" class="add_img">' +
                '</div>'
        }
        car_data.insertAdjacentHTML("beforeend", str)

        // + 添加显示事件
        $(".add_img").on("click", function () {
            clearTimeout(timeout)
            let car_id = $(this).prevAll()[1].innerText
            timeout = setTimeout(add_show(car_id), 300)
        })
    })
} initcar()

// 模糊查询
{
    let timeout;
    let car_form_input = document.querySelector("#car_form input")
    car_form_input.addEventListener("input", function () {

        $('#dir_data').html('')

        if (car_form_input.value) {
            let url = ip + ":" + api_port_1 + "/get_search/" + car_form_input.value
            // 清除timeout 用于节流
            clearTimeout(timeout);
            timeout = setTimeout(function () {
                ajax_method(url, null, "Get", (data) => {
                    if (data.length > 2) {
                        $("#data_hint").css({ display: "none" })
                        let str = ""
                        let res = JSON.parse(data);
                        for (let i = 0; i < res.length; i++) {
                            str += '<div class="car_row car_row_li">' +
                                '<div class="car_d1">' + res[i][0] + '</div>' +
                                '<div class="car_d2">' + res[i][1] + '</div>' +
                                '<img src="img/+.png" alt="添加到显示" title="添加到显示" class="add_img">' +
                                '</div>'
                        }
                        // $('#dir_data').html("")
                        $("#dir_data").html(str)
                        // + 添加显示事件
                        $(".add_img").on("click", function () {
                            clearTimeout(timeout)
                            let car_id = $(this).prevAll()[1].innerText
                            timeout = setTimeout(add_show(car_id), 300)
                        })
                    } else {
                        $("#dir_data").html('')
                        $(".add_img").on("click", function () {
                            clearTimeout(timeout)
                            let car_id = $(this).prevAll()[1].innerText
                            timeout = setTimeout(add_show(car_id), 300)
                        })
                    }
                })
            }, 300);
        }
        else {
            setTimeout(initcar(), 100)
        }

    })
}

// ------------------弹窗------------------------------------------------
$("#dir_data").click(function (e) {
    $(".car_show").attr("disabled", false)
    pop_up(e)
})

$("#list_data").click(function (e) {
    if (e.target.getAttribute("src")) {
    } else {
        $(".car_show").attr("disabled", "disabled")
        pop_up(e)
    }
})

function pop_up(e) {
    let class_arry = ["car_d1", "car_d2", "car_d3"];
    let e_class = e.target.getAttribute("class");
    for (let i = 0; i < class_arry.length; i++) {
        if (e_class === class_arry[i]) {
            let id_node = e.target.parentNode.firstChild
            let url = ip + ":" + api_port_1 + "/get_car_data/" + id_node.innerText
            fetch(url, {
                method: 'GET',
            }).then(res => {
                return res.json()
            }).then(res => {
                $("#data_id").text(res[0][0])
                $("#data_car_id").text(res[0][1])
                $("#data_car_color").text(res[0][2])
                $("#data_car_name").text(res[0][3])
                $("#data_car_phone").text(res[0][4])
                $("#data_car_section").text(res[0][5])
                $("#data_car_type").text(res[0][6])
                $("#data_car_nat").text(res[0][7])
                $("#data_car_state").text(res[0][8])
                $("#data_car_bz").text(res[0][9])
                $(".car_data_img img").attr("src", res[0][10])
            }).then(() => {
                $(".car_data").css({ display: "inline" })
            })
        }
    }
}
// 关闭
$(".img_close").click(() => {
    $(".car_data").css({ display: "none" })
})

// 拖动
$("#car_data_title").mousedown((ev) => {
    let ifmove = true
    let box = $(".car_data")
    let e = ev || Event

    let f_x = e.clientX
    let f_y = e.clientY

    let f_box_x = box.offset().left;
    let f_box_y = box.offset().top;

    let x = f_x - f_box_x;
    let y = f_y - f_box_y;

    $(document).mousemove((ev) => {
        if (ifmove) {
            let e = ev || Event

            let l_x = e.clientX
            let l_y = e.clientY

            let l_box_x = l_x - x
            let l_box_y = l_y - y

            if (l_box_x < 0){
                l_box_x = 0 
            }
            if(l_box_x > 866){
                l_box_x = 866
            }
            if(l_box_y < 0 ){
                l_box_y = 0
            }
            if(l_box_y > 135){
                l_box_y = 135
            }

            box.css({ "left": l_box_x + "px", "top": l_box_y + "px"})
        }
    }).mouseup(() => {
        ifmove = false
    })
})



// -------------------------------车辆显示-------------------------------------
let timeout;
function add_show(car_id) {
    let url = ip + ":" + api_port_1 + "/get_car_path/" + car_id
    ajax_method(url, null, "Get", (data) => {
        let paths = JSON.parse(JSON.parse(data))
        car_show(car_id, paths)
    }
    )
}
// 添加显示
$(".car_show").click(() => {
    clearTimeout(timeout)
    let car_id = $("#data_car_id").text()
    timeout = setTimeout(add_show(car_id), 300)
})

// 查看历史行驶轨迹
$(".his_button").click(()=>{
    let car_id = $("#data_car_id").text()
    localStorage.setItem("car_id",car_id)
    window.open("hispaths.html")
})


function car_show(car_id,car_paths){
    let log = true

    let all_show_car = $("#list_data .car_d1")
    
    for (let i =0; i < all_show_car.length; i++){

        if (all_show_car[i].innerText === car_id){
            log = false;
        }
    }
    if (log) {
        let url = ip + ":" + api_port_1 + "/get_car_data/" + car_id
        fetch(url, {
            method: "GET",
        }).then(res => {
            return res.json()
        }).then(res => {
            $("#list_data").append('<div class="car_row car_row_li">' +
                `<div class="car_d1">${car_id}</div>` +
                `<div class="car_d2">${res[0][2]}</div>` +
                `<div class="car_d3">行驶中</div>` +
                ' <img src="img/stop.png" alt="暂停" title="暂停" class="stop_img">' +
                '<img src="img/-.png" alt="移除显示" title="移除显示" class="sub_img">' +
                '</div>')
            car_init(car_id, car_paths)
        }).then(() => {
            $(".stop_img").off("click").on("click", function () {
                if (this.alt == "暂停") {
                    this.src = "img/start.png";
                    this.alt = "开始";
                    this.title = "开始";
                    let car_id = (this.parentNode.children[0].innerText);
                    car_run[car_id].car.pauseMove()
                } else {
                    this.src = "img/stop.png";
                    this.alt = "暂停";
                    this.title = "暂停";
                    let car_id = (this.parentNode.children[0].innerText);
                    car_run[car_id].car.resumeMove();
                }
            })
            $(".sub_img").off("click").on("click",function(){
                let father_div = this.parentNode
                let car_id = this.parentNode.children[0].innerText;

                // 删除全局对象
                delete car_run["car_" + car_id]  

                // 移除html
                father_div.remove()

                // 移除点标记
                car_run[car_id].car.setMap(null);
            })
        }
        )
    }
}


// 构造车辆类
function ACar(car_id, paths) {
    this.num = car_id;
    this.paths = paths
    this.interval
    this.car_icon = new AMap.Icon({
        size: new AMap.Size(52, 26),    // 图标尺寸
        image: 'img/car3.png',  // Icon的图像
        imageOffset: new AMap.Pixel(0, 0),  // 图像相对展示区域的偏移量，适于雪碧图等
        imageSize: new AMap.Size(40, 20),   // 根据所设置的大小拉伸或压缩图片
    });
    this.car = new AMap.Marker({
        map: map,
        position: this.paths[0],
        icon: this.car_icon,
        offset: new AMap.Pixel(-20, -10),
        title: "车牌号:" + car_id,
        autoRotation: true,
        // angle:90,
    })
    this.add = function () {
        map.add(this.car)
        this.car.moveAlong(this.paths, car_v);
    }
    this.run = function () {
        let url = ip + ":" + api_port_1 + "/get_car_path/" + car_id
        // GPS 更新
        function x() {
            fetch(url, {
                method: "GET"
            }).then(res => {
                return res
            }).then(res => {
                return res.json()
            }).then(res => {
                let paths = JSON.parse(res);
                let all_d1 = $("#table_list .car_d1")
                car_paths[car_id] = paths
                console.log(`${car_id}:\n[${paths}]`)

                for (let i = 0; i < all_d1.length; i++) {
                    if (all_d1[i].innerText === car_id) {
                        let all_stop = $("#table_list .stop_img")
                        if (all_stop[i - 1].alt === "暂停") {
                            car_run[car_id].car.moveAlong(car_paths[car_id], car_v)
                        }
                    }
                }
                if (paths.length < 2) {
                    for (let i = 0; i < all_d1.length; i++) {
                        if (all_d1[i].innerText === car_id) {
                            $("#table_list .car_d3")[i].innerText = "停车"
                        }
                    }
                } else {
                    for (let i = 0; i < all_d1.length; i++) {
                        if (all_d1[i].innerText === car_id) {
                            $("#table_list .car_d3")[i].innerText = "行驶中"
                        }
                    }
                }
            }
                // ).catch(err => {
                //     console.log("!!!");
                // }
            )
        }
        x();
        this.interval = setInterval(x, 10000);
    }
}

function car_init(car_id,car_paths){
    car_run[car_id]= new ACar(car_id,car_paths)
    car_run[car_id].add()
    car_run[car_id].run()
    // car_run[car_id].car.moveAlong(car_paths[car_id],30)
}

// 1.循环更新数据 2.隔段时间暂停 从对象重新拿paths